package com.hy.storage.service.impl;

import com.hy.storage.domain.Storage;
import com.hy.storage.mapper.StorageMapper;
import com.hy.storage.service.StorageServiceSaga;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class StorageServiceImplSaga implements StorageServiceSaga {
    @Resource
    StorageMapper storageMapper;

    @Override
    public boolean reduceStockBySaga(String businessKey, String storageException, long productId, long quantity) {
        log.info("--->库存扣减数量开始，业务id:{},商品Id:{},扣减数量:{}", businessKey, productId, quantity);
        Storage storage = storageMapper.getStorageByPid(productId);
        // 减总数  加售出数
        storage.setTotal(storage.getTotal() - quantity);
        storage.setSold(storage.getSold() + quantity);

        int res = storageMapper.updateByPrimaryKeySelective(storage);
        if ("true".equals(storageException)){
            throw new RuntimeException("库存扣减数量失败！");
        }
        log.info("--->库存扣减数量结束，业务id:{},商品Id:{},扣减结果:{}", businessKey, productId, res);
        return true;
    }

    @Override
    public boolean storageCompensate(String businessKey, long productId, long quantity) {
        log.info("--->库存补偿数量开始，业务id:{},商品Id:{},补偿数量:{}", businessKey, productId, quantity);
//        int res = storageMapper.storageCompensate(productId, quantity);
        Storage storage = storageMapper.getStorageByPid(productId);
        // 减总数  加售出数
        storage.setTotal(storage.getTotal() + quantity);
        storage.setSold(storage.getSold() - quantity);

        int res = storageMapper.updateByPrimaryKeySelective(storage);

        log.info("--->库存补偿数量结束，业务id:{},商品Id:{},补偿结果:{}", businessKey, productId, res);
        return true;
    }
}
